﻿//*****************************************************************************
//
//  Copyright 2008 IT Cloud Company
//
//  This software is available under the Microsoft Public License.  Please
//  read the license agreement at http://opensource.org/licenses/ms-pl.html
//  before using the software.
//
//  Authors:
//    Don Song (don@itcloud.com)
//
//*****************************************************************************

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace HeadLinx.AD.Common
{
    public class HeadLinxPropertyMap : Dictionary<string, HeadLinxPropertyValueCollection>
    {
        public string TryGetPropertyAsString(string propName)
        {
            HeadLinxPropertyValueCollection propValues;

            if (this.TryGetValue(propName, out propValues))
            {
                return propValues.ToString();
            }

            return null;
        }

        public byte[] TryGetByteArrayProperty(string propName)
        {
            HeadLinxPropertyValueCollection propValues;

            if (this.TryGetValue(propName, out propValues))
            {
                object value = propValues.TryGetFirstValue();
                return value as System.Byte[];
            }

            return null;
        }

        public void AddProperty(string propName, object value)
        {
            HeadLinxPropertyValueCollection propValues;

            if (!this.TryGetValue(propName, out propValues))
            {
                propValues = new HeadLinxPropertyValueCollection();
                this[propName] = propValues;
            }

            propValues.Add(value);
        }
    }

    public class HeadLinxPropertyValueCollection : Collection<object>
    {
        public override string ToString()
        {
            return this.ConcatValuesAsString(",");
        }

        public object TryGetFirstValue()
        {
            if (this.Count != 0)
            {
                return this[0];
            }

            return null;
        }

        public string ConcatValuesAsString(string delimiter)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < this.Count; ++i)
            {
                object value = this[i];

                if (value != null)
                {
                    sb.Append(value.ToString());
                }
                else
                {
                    sb.Append("<null>");
                }

                if ((i + 1) < this.Count)
                {
                    // More items, separate with caller-specified delimiter.
                    sb.Append(delimiter);
                }
            }

            return sb.ToString();
        }
    }
}
